// VueCli 脚手架为了开发者更好的管理项目中路由，把路由相关的配置用独立文件维护
import Vue from 'vue'
import VueRouter from 'vue-router'
// 用作页面的 vue 文件导入
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Userinfo from '@/views/Userinfo.vue'
import Useredit from '@/views/Useredit.vue'
import Attention from '@/views/Attention.vue'
import Collect from '@/views/Collect.vue'
import Detail from '@/views/Detail.vue'
import Comment from '@/views/Comment.vue'
import UserComment from '@/views/UserComment.vue'
import Search from '@/views/Search.vue'
import Manage from '@/views/Manage.vue'

// Token 导入
import { getToken } from '@/utils/myToken'

// 导入测试用的页面
// import Test from '@/demo/TestFollows.vue'
// import Test from '@/demo/TestList.vue'
// import Test from '@/demo/TestDiguiPage.vue'
import Test from '@/demo/TestCommentDiguiPage.vue'

// 安装 Vue 路由插件
Vue.use(VueRouter)

// 路由配置表 - 通过匹配某个路径切换到某个组件
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
  },
  {
    path: '/detail/:id',
    name: 'Detail',
    component: Detail,
  },
  // 个人中心
  {
    path: '/userinfo',
    name: 'Userinfo',
    component: Userinfo,
    meta: {
      isAuth: true,
    },
  },
  {
    path: '/useredit',
    name: 'Useredit',
    component: Useredit,
    meta: {
      isAuth: true,
    },
  },
  // 我的关注
  {
    path: '/attention',
    name: 'Attention',
    component: Attention,
    meta: {
      isAuth: true,
    },
  },
  {
    path: '/collect',
    name: 'Collect',
    component: Collect,
    meta: {
      isAuth: true,
    },
  },
  // 用于测试的页面
  {
    path: '/test',
    name: 'Test',
    component: Test,
  },
  {
    path: '/comment/:id', // 注意这里使用动态路由
    name: 'Comment',
    component: Comment,
  },
  {
    path: '/usercomment',
    name: 'UserComment',
    component: UserComment,
    meta: {
      isAuth: true,
    },
  },
  {
    path: '/search',
    name: 'Search',
    component: Search,
  },
  {
    path: '/manage',
    name: 'Manage',
    component: Manage,
  },
]

// 创建路由实例，需传入路由配置表
const router = new VueRouter({
  routes,
})

// 使用 router.beforeEach 注册一个全局前置守卫：
router.beforeEach((to, from, next) => {
  // console.log('去往哪个城市(页面) -- to', to)
  // console.log('来自哪个城市(页面) - from', from)
  // console.log('下一个 - next 是一个函数', next)
  // 现在要去往 /userinfo页面，但是如果是没有登录，就先跳转到登录页
  if (to.meta.isAuth === true) {
    if (!getToken()) {
      return router.replace('/login')
    }
  }
  // 没有特殊情况的页面，统一方向，代码的最后一定要记得放行，忘记放行就看不到任何页面了
  next()
})

// 导出路由实例，提供给 src/main.js 入口文件使用
export default router
